<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="客户名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入手机"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="微信" prop="weixin">
        <el-input
          v-model="queryParams.weixin"
          placeholder="请输入微信"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="渠道" prop="source">
        <el-select
          v-model="queryParams.source"
          clearable
          placeholder="请选择渠道"
          @change="handleQuery"
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CRM_CUSTOMER_SOURCE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="跟踪状态" prop="followStatus">
        <el-select
          v-model="queryParams.followStatus"
          clearable
          placeholder="请选择跟踪状态"
          style="width: 100%"
          @change="handleQuery"
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CRM_FOLLOW_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          >
            <span :style="{ color: getFollowStatusColor(dict.label) }">{{ dict.label }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="跟踪人" prop="stalker">
        <el-select
          v-model="queryParams.stalker"
          clearable
          placeholder="请选择跟踪人"
          style="width: 100%"
          @change="handleQuery"
          class="!w-240px"
        >
          <el-option
            v-for="user in userList"
            :key="user.id"
            :label="user.nickname"
            :value="user.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="签单时间" prop="stalker">
        <el-date-picker
          v-model="queryParams.signTime"
          type="daterange"
          value-format="YYYY-MM-DD"
          placeholder="选择签单时间"
          class="!w-240px"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="门店" prop="storageId">
        <el-select
          v-model="queryParams.storageId"
          clearable
          placeholder="请选择门店"
          style="width: 100%"
          @change="handleQuery"
          class="!w-240px"
        >
          <el-option
            v-for="storage in storageList"
            :key="storage.storageId"
            :label="storage.storageName"
            :value="storage.storageId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          type="daterange"
          value-format="YYYY-MM-DD"
          placeholder="选择创建时间"
          class="!w-240px"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="回访时间" prop="nextTime">
        <el-select
          v-model="queryParams.returnValue"
          clearable
          placeholder="请选择回访时间"
          style="width: 100%"
          @change="handleQuery"
          class="!w-240px"
        >
          <el-option label="已过期" value="0" />
          <el-option label="三天内" value="3" />
          <el-option label="一周内" value="7" />
          <el-option label="两周内" value="14" />
          <el-option label="一个月内" value="30" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['crm:customer:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="selectCustomers.length === 0"
          @click="handleDelete(selectCustomers.map((item: CustomerVO) => item.id))"
          v-hasPermi="['crm:customer:delete']"
          v-if="isAdministrator()"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleSelectionChange"
      class="custom-table"
    >
      <el-table-column type="selection" width="40" />
      <el-table-column type="index" width="50" />
      <el-table-column label="门店" align="center" prop="storageName" width="120">
        <template #default="scope">
          <div class="clickable-storage-name" @click="openForm('update', scope.row.id)">{{
            scope.row.storageName
          }}</div>
        </template>
      </el-table-column>

      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="客户名称" align="center" prop="name" width="100" />
      <el-table-column label="手机" align="center" prop="mobile" width="120">
        <template #default="scope">
          <div v-if="scope.row.mobileRepeat" style="color: #ff0000; font-weight: bold !important">{{
            scope.row.mobile
          }}</div>
          <div v-else>{{ scope.row.mobile }}</div>
        </template>
      </el-table-column>
      <el-table-column label="微信" align="center" prop="weixin" width="120">
        <template #default="scope">
          <div v-if="scope.row.weixinRepeat" style="color: #ff0000; font-weight: bold !important">{{
            scope.row.weixin
          }}</div>
          <div v-else>{{ scope.row.weixin }}</div>
        </template>
      </el-table-column>
      <el-table-column label="客户需求" align="center" prop="demand" width="120" />
      <el-table-column label="跟踪状态" align="center" prop="followStatus" width="120">
        <template #default="scope">
          <div
            :style="{
              color: getFollowStatusColor(
                getIntDictOptions(DICT_TYPE.CRM_FOLLOW_STATUS)?.find(
                  (item) => item.value == scope.row.followStatus
                )?.label || ''
              ),
              'font-weight': 'bold !important'
            }"
            class="follow-status-text"
          >
            {{
              getIntDictOptions(DICT_TYPE.CRM_FOLLOW_STATUS)?.find(
                (item) => item.value == scope.row.followStatus
              )?.label
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="回访时间" align="center" prop="nextTime" width="180px">
        <template #default="scope">
          <div v-if="scope.row.nextTime">
            <div
              :style="{
                color: getRemainingDaysColor(scope.row.nextTime),
                'font-weight': 'bold !important'
              }"
            >
              {{ getRemainingDays(scope.row.nextTime) }}
            </div>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>

      <el-table-column label="备注" align="center" prop="remark" width="120" />

      <el-table-column label="渠道" align="center" prop="source" width="120">
        <template #default="scope">
          <div
            >{{
              getIntDictOptions(DICT_TYPE.CRM_CUSTOMER_SOURCE)?.find(
                (item) => item.value == scope.row.source
              )?.label
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="详细地址" align="center" prop="detailAddress" width="120" />

      <el-table-column label="跟踪人" align="center" prop="stalker" width="120">
        <template #default="scope">
          <div>{{ userList?.find((item) => item.id == scope.row.stalker)?.nickname }} </div>
        </template>
      </el-table-column>
      <el-table-column label="需求类型" align="center" prop="tags" width="120">
        <template #default="scope">
          <div
            >{{
              getIntDictOptions(DICT_TYPE.DEMAND_TYPE)?.find((item) => item.value == scope.row.tags)
                ?.label
            }}
          </div>
        </template>
      </el-table-column>

      <el-table-column
        label="下次回访时间"
        align="center"
        prop="nextTime"
        :formatter="dateFormatter2"
        width="180px"
      />
      <el-table-column
        label="签单时间"
        align="center"
        prop="signTime"
        :formatter="dateFormatter2"
        width="180px"
      />

      <el-table-column label="签单金额" align="center" prop="inPrice" width="120" />

      <!-- <el-table-column label="成交状态" align="center" prop="dealStatus">
        <template #default="scope">
          <div>
            <el-tag v-if="scope.row.dealStatus === 1" type="success">成交</el-tag>
            <el-tag v-else type="danger">未成交</el-tag>
          </div>
        </template>
      </el-table-column> -->
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <CustomerForm ref="formRef" @success="getList" />
  <RecordForm ref="recordFormRef" />
  <SmsTemplateSendForm ref="smsTemplateSendFormRef" />
  <MailTemplateSendForm ref="mailTemplateSendFormRef" />
</template>

<script setup lang="ts">
import { dateFormatter, dateFormatter2, formatDate } from '@/utils/formatTime'
import { CustomerApi, CustomerVO } from '@/api/crm/crmcustomer'
import CustomerForm from './CustomerForm.vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import RecordForm from '@/views/crm/crmrecord/RecordForm.vue'
import SmsTemplateSendForm from '@/views/components/sms/SmsTemplateSendForm.vue'
import MailTemplateSendForm from '@/views/components/email/MailTemplateSendForm.vue'

import { BaseStorageApi, BaseStorageVO } from '@/api/crm/basestorage'
import type { UserVO } from '@/api/system/user'
import * as UserApi from '@/api/system/user'
import { isAdministrator } from '@/hooks/web/useCache'
/** 客户 列表 */
defineOptions({ name: 'CrmCustomer' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<CustomerVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined as string | undefined,
  mobile: undefined as string | undefined,
  telephone: undefined as string | undefined,
  dealStatus: undefined as number | undefined,
  level: undefined as number | undefined,
  industry: undefined as string | undefined,
  tags: undefined as string | undefined,
  source: undefined as number | undefined,
  remark: undefined as string | undefined,
  userId: undefined as number | undefined,
  // province: undefined,
  // city: undefined,
  // area: undefined,
  weixin: undefined as string | undefined,
  qq: undefined as string | undefined,
  relation: 'my' as string,
  followStatus: undefined as number | undefined,
  stalker: undefined as number | undefined,
  signTime: undefined as any | undefined,
  storageId: undefined as number | undefined,
  storageName: undefined as string | undefined,
  createTime: undefined as any | undefined,
  returnValue: undefined as string | undefined
})
const queryFormRef = ref() // 搜索的表单
const selectCustomers = ref([])
const isDisabled = ref(true)
const userList = ref<UserVO[]>([]) // 用户列表
const storageList = ref<BaseStorageVO[]>([]) // 门店列表

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await CustomerApi.getCustomerPage(queryParams)
    list.value = data.list
    list.value.map((value) => {
      if (value.tags && typeof value.tags === 'string' && value.tags !== '') {
        value.tags = value.tags.split(',')
      } else if (!value.tags || value.tags === '') {
        value.tags = []
      }
    })
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const handleSelectionChange = (val) => {
  if (val.length > 0) {
    isDisabled.value = false
  }
  selectCustomers.value = val
}

/** 搜索按钮操作 */
const handleQuery = () => {
  if (
    queryParams.createTime &&
    Array.isArray(queryParams.createTime) &&
    queryParams.createTime.length === 2
  ) {
    const startDate = formatDate(queryParams.createTime[0], 'YYYY-MM-DD')
    const endDate = formatDate(queryParams.createTime[1], 'YYYY-MM-DD')

    queryParams.createTime[0] = startDate + ' 00:00:00'

    queryParams.createTime[1] = endDate + ' 23:59:59'
  }
  if (
    queryParams.signTime &&
    Array.isArray(queryParams.signTime) &&
    queryParams.signTime.length === 2
  ) {
    // 格式化日期为 YYYY-MM-DD 格式，然后添加时间
    const startDate = formatDate(queryParams.signTime[0], 'YYYY-MM-DD')
    const endDate = formatDate(queryParams.signTime[1], 'YYYY-MM-DD')

    queryParams.signTime[0] = startDate + ' 00:00:00'

    queryParams.signTime[1] = endDate + ' 23:59:59'
  }
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

const recordFormRef = ref()

/** 删除按钮操作 */
const handleDelete = async (ids: number[]) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await CustomerApi.deleteCustomer(ids)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

const smsTemplateSendFormRef = ref()

const mailTemplateSendFormRef = ref()

/** 计算剩余天数 */
const getRemainingDays = (nextTime: string) => {
  if (!nextTime) return ''
  const nextDate = new Date(nextTime)
  const now = new Date()

  // 设置时间为当天的00:00:00进行比较
  const nextDateStart = new Date(nextDate.getFullYear(), nextDate.getMonth(), nextDate.getDate())
  const nowDateStart = new Date(now.getFullYear(), now.getMonth(), now.getDate())

  const diffTime = nextDateStart.getTime() - nowDateStart.getTime()
  const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))

  if (diffDays < 0) {
    return `已过期 ${Math.abs(diffDays)}天`
  } else if (diffDays === 0) {
    return '剩余0天'
  } else {
    return `剩余 ${diffDays}天`
  }
}

/** 获取剩余天数的颜色 */
const getRemainingDaysColor = (nextTime: string) => {
  if (!nextTime) return ''
  const nextDate = new Date(nextTime)
  const now = new Date()

  // 设置时间为当天的00:00:00进行比较
  const nextDateStart = new Date(nextDate.getFullYear(), nextDate.getMonth(), nextDate.getDate())
  const nowDateStart = new Date(now.getFullYear(), now.getMonth(), now.getDate())

  const diffTime = nextDateStart.getTime() - nowDateStart.getTime()
  const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))

  if (diffDays <= 3) {
    return '#f56c6c' // 红色 - 3天内到期
  } else {
    return '#67c23a' // 绿色 - 正常
  }
}

/** 获取跟踪状态的颜色 */
const getFollowStatusColor = (statusLabel: string) => {
  if (statusLabel === '意向') {
    return '#409eff' // 🔵 蓝色 - 意向
  } else if (statusLabel === '即将签单') {
    return '#f56c6c' // 🔴 红色 - 即将签单
  } else if (statusLabel === '已签单') {
    return '#67c23a' // 🟢 绿色 - 已签单
  } else if (statusLabel === '已放弃') {
    return '#909399' // 灰色 - 已放弃
  } else if (statusLabel === '冻结客户') {
    return '#606266' // 深灰色 - 冻结客户
  } else if (statusLabel === '已转交') {
    return '#e6a23c' // 🟡 黄色 - 已转交
  } else {
    return '#606266' // 默认颜色
  }
}

/** 初始化 **/
onMounted(async () => {
  getList()

  // 获取用户列表
  try {
    const userData = await UserApi.getAllUserFilter()

    userList.value = userData ? userData : []
  } catch (error) {
    console.error('获取用户列表失败:', error)
  }

  // 获取门店列表
  try {
    const storageData = await BaseStorageApi.getBaseStorageAllDesc()
    storageList.value = storageData ? storageData : []
  } catch (error) {
    console.error('获取门店列表失败:', error)
  }
})
</script>

<style scoped>
.follow-status-text {
  font-weight: bold !important;
}

/* 可点击的门店名称样式 */
.clickable-storage-name {
  cursor: pointer;
  color: #409eff;
  text-decoration: none;
  transition: all 0.3s ease;
}

.clickable-storage-name:hover {
  color: #66b1ff;
  text-decoration: underline;
  font-weight: bold;
}

/* 自定义表格滚动条样式 */
/* 只调整滚动条宽度 */
:deep(.el-scrollbar__bar.is-horizontal) {
  height: 12px !important; /* 横向滚动条高度 - 只调整宽度 */
}

/* 确保滚动条始终显示 */
:deep(.el-table__body-wrapper) {
  overflow-x: auto !important;
}

/* 针对表格容器的滚动条样式 */
.custom-table :deep(.el-table__body-wrapper) {
  overflow-x: auto !important;
}
</style>
